package com.jeesite.modules.kj.api.wechatUtils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @desc   使用token验证用户是否登录
 * @author feng
 **/
@Slf4j
public class TokenUtils {
    //设置过期时间 两天后过期
    private static final long EXPIRE_DATE=3600*24*10*1000;
    //token秘钥
    private static final String TOKEN_SECRET = "ZCfasfhuaUUHufguGuwu2020BQWEkauiji";

    public static String token(String openid){

        String token = "";
        try {
            //过期时间
            Date date = new Date(System.currentTimeMillis()+EXPIRE_DATE);
            //秘钥及加密算法
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            //设置头部信息
            Map<String,Object> header = new HashMap<>();
            header.put("typ","JWT");
            header.put("alg","HS256");
            //携带username，password信息，生成签名
            token = JWT.create()
                    .withHeader(header)
                    .withClaim("openid",openid).withExpiresAt(date)
                    .sign(algorithm);
        }catch (Exception e){
            log.error("生成token异常："+e.getMessage());
            return  null;
        }
        return token;
    }

    public static String verify(String token){
        /**
         * @desc   验证token，通过返回true
         * @params [token]需要校验的串
         **/
        try {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            return JWT.decode(token).getClaim("openid").asString();
        }catch (Exception e){
            log.error("token1111"+ token + "检验不通过:"+e.getMessage());
            return  null;
        }
    }


    public static void main(String[] args){
        TokenUtils.token("1425637245592129536");
    }

}
